'use strict';

import { merchanthistoryModel } from "../model/merchanthistory";
import { ServiceBase, Exceptions } from '../kalend';
import { customer_accountService } from "./customer_account";
import { merchantService } from "./merchant";
import { wineService } from "./wine";
import { mealService } from "./meal";
import { customer_orderwineService } from "./customer_orderwine";
import { platform_userService } from "./platform_user";
import _ = require("underscore");
import { common } from "../middleware/common";
var moment = require('moment');

class MerchanthistoryService extends ServiceBase {
    constructor() {
        super(merchanthistoryModel)
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const mid = params.mid;
        const starttime = params.starttime;
        const endtime = params.endtime;

        let filter: any = {};
        if (mid) {
            filter.merchantid = mid;
        }
        if (starttime) {
            filter.updateTime = { '$gte': new Date(moment(new Date(starttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.updateTime = { '$lte': new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        let data: any = await super.queryPagination(offset, limit, {
            filter: filter,
            populateOptions: [{
                path: 'customerid',
                select: 'nickname'
            },
            {
                path: 'customerorderid',
                select: 'code'
            },
            {
                path: 'merchantid',
                select: 'name'
            }
            ]
        });
       
        data.rows = data.rows.map((item: any) => {
            item.nickname = item.customerid ? item.customerid.nickname : '';
            item.ordercode = item.customerorderid ? item.customerorderid.code : '';
            item.mername = item.merchantid ? item.merchantid.name : '';
            return item;
        });
        //let moneyTotal = eval(_.pluck(data.rows, 'money').join('+'));
        //let coninsTotal = eval(_.pluck(data.rows, 'conins').join('+'));
        // let ratemoneyTotal = eval(_.pluck(data.rows, 'ratemoney').join('+'));
        // let agentrewardTotal = eval(_.pluck(data.rows, 'agentreward').join('+'));
        let moneyTotal = 0;
        let coninsTotal = 0;
        let mealTotal = 0;
        const dataall= await this.queryAll({filter: filter, select:'addmoney coninscount addmeal'});
        dataall.map((a)=>{
            moneyTotal = common.add(moneyTotal, a.addmoney);
            coninsTotal = common.add(coninsTotal, a.coninscount);
            mealTotal = common.add(mealTotal, a.addmeal);
        })
        if (moneyTotal || mealTotal) {
            data.footTotal = `共计 入账餐费【${moneyTotal || 0}】元，入账餐币【${mealTotal || 0}】元，消费酒水【${coninsTotal}】瓶`;
        }
        return data;
    }
    /** 生成商户消费记录及更新商户余额-用户买单 */
    async buildhistory(order: any) {
        const merchant = await merchantService.querySingle({ _id: order.merchantid }, { select: 'name code balance coinbalance mealbalance agent' })
        let doc: any = {
            name: merchant.name,
            code: merchant.code,
            conins: order.conins,
            coninscount: order.coninscount,
            meal: order.meal,
            merchantid: order.merchantid,
            customerid: order.customerid,
            customerorderid: order._id,
            money: order.money,
            mealmoney: order.mealmoney,
            winemoney: order.winemoney,
            rate: order.rate,
            ratemoney: order.ratemoney,
            ratemeal: order.ratemeal,
            // agentrate: order.agentrate,
            // agentreward: order.agentreward,
            type: 1
        };
        let updadoc: any = {};

        if (order.winelist && order.winelist.length > 0) {
            console.log('买单：生成消费酒水记录');
            let newitems = order.winelist.map((a: any) => {
                let b: any = {
                    count: a.count
                };
                b.wineid = a._id;
                b.orderid = order._id;
                return b
            });
            customer_orderwineService.createMany(newitems);
            console.log('买单：生成消费酒水记录---成功');
        }

        /** 餐厅订单奖励大使金额入账 */
        if (merchant.agent) {
            if (order.agentreward > 0) {
                doc.agent = merchant.agent;
                doc.agentrate = order.agentrate;
                doc.agentreward = order.agentreward;
                console.log(`买单：本次用户消费金额【${order.money}】，所属品牌大使获得【${doc.agentreward}】`);
                platform_userService.updateAgentBalance({ agent: merchant.agent, addm: Number(doc.agentreward) })
            }
        }
        /** 餐厅酒币扣除 */
        if (doc.coninscount > 0) {
            doc.coinbalance = (merchant.coinbalance || 0) - doc.coninscount;
            updadoc.coinbalance = doc.coinbalance;
        }

        /** 餐厅实际入账 */
        let ssmoney = common.sub(common.sub(doc.money, doc.winemoney), doc.ratemoney);
        doc.addmoney = ssmoney;

        /** 餐厅餐币入账 */
        if (doc.ratemeal > 0) {
            // 商户获取餐币的平台抽成后比例
            //const ratemeal = common.div(common.mul(doc.meal, order.rate), 100);
            const addmeal = common.sub(doc.meal, doc.ratemeal);
            doc.addmeal = addmeal;
            doc.mealbalance = common.add(merchant.mealbalance, addmeal);
            updadoc.mealbalance = doc.mealbalance;
            console.log(`买单：本次用户消费餐币【${doc.meal}】个，商家获得【${addmeal}】个餐币`);

            // 商户获取人民币= 餐费-餐币抽成
            //ssmoney = common.sub(ssmoney, ratemeal);
        }

        doc.balance = common.add(merchant.balance, ssmoney);
        updadoc.balance = doc.balance;
        console.log(`买单：本次用户消费金额【${order.money}】，商家获得【${ssmoney}】元`);

        merchantService.update(merchant._id, updadoc);
        console.log('买单：准备增加商户余额、餐币余额，扣减商户酒币---成功');
        this.create(doc);
        console.log('买单：增加商户账户更新记录---成功');


        /** 餐厅订单，会员酒币、餐币账户更新 */
        console.log('买单：准备减扣用户酒币、餐币');
        let userdata = await customer_accountService.querySingle({ _id: order.customerid, status: {$ne: 0 }}, { select: 'integral coinbalance mealbalance' });
        let coinbalance, mealbalance;
        if (doc.conins > 0) {
            coinbalance = userdata.coinbalance - doc.conins;
            console.log('买单：增加酒币消费记录');
            wineService.create({
                userid: order.customerid,
                merchantid: order.merchantid,
                originwine: userdata.coinbalance,
                coinbalance: coinbalance,
                conins: doc.conins,
                source: 1
            });
            console.log('买单：增加酒币消费记录---成功');
            customer_accountService.update(order.customerid, {coinbalance: coinbalance});
            console.log('买单：减扣用户酒币---成功');
        }
        if (doc.meal > 0) {
            mealbalance = userdata.mealbalance - doc.meal;
            console.log('买单：增加餐币消费记录');
            mealService.create({
                userid: order.customerid,
                originmeal: userdata.mealbalance,
                mealbalance: mealbalance,
                meal: doc.meal,
                source: 1
            });
            console.log('买单：增加餐币消费记录---成功');
            customer_accountService.update(order.customerid, {mealbalance: mealbalance});
            console.log('买单：减扣用户餐币---成功');
        }
        console.log('买单：减扣用户酒币、餐币---成功');

        
    }
}

export const merchanthistoryService = new MerchanthistoryService();